import React, { Suspense } from 'react'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import BasicLayout from '@/layouts/basicLayout.jsx'
import LoginLayout from '@/layouts/loginLayout.jsx'
import Loading from '@/components/loading'
import routes from './routes'

const AppRouter = (routeProps) => {
  const renderSubRoute = (route) => (
    <>
      {route.children && route.children.length > 0 && (
        <Suspense fallback={<Loading />}>
          <Switch>
            {route.children.map((child, j) => {
              return (
                <Route path={child.path} exact={child.exact} key={j} component={child.component} />
              )
            })}
          </Switch>
        </Suspense>
      )}
    </>
  )
  const renderRoute = (routes) => {
    return (
      <Suspense fallback={<Loading />}>
        <Switch>
          {routes.map((route, i) => (
            <Route
              path={route.path}
              exact={route.exact || false}
              key={route.key}
              render={(props) => (
                <>
                  {route.component
                    ? React.createElement(route.component, {
                        ...props,
                        children: renderSubRoute(route, props)
                      })
                    : renderSubRoute(route, props)}
                </>
              )}
            />
          ))}
        </Switch>
      </Suspense>
    )
  }
  return (
    <Router>
      <Switch>
        <Route
          path="/login"
          render={() => (
            <LoginLayout {...routeProps} renderRoute={() => renderRoute(routes.loginRoutes)} />
          )}
        />
        <Route
          path="/"
          render={() => (
            <BasicLayout {...routeProps} renderRoute={() => renderRoute(routes.mainRoutes)} />
          )}
        />
      </Switch>
    </Router>
  )
}

export default AppRouter
